package com.lilicould.service;

import com.google.gson.Gson;
import com.lilicould.dao.CollegeDao;
import com.lilicould.entity.Colleges;
import com.lilicould.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;


public class CollegeService {
    public String getAllCollege() {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            CollegeDao collegeDao = sqlSession.getMapper(CollegeDao.class);
            return new Gson().toJson(collegeDao.getAllCollege());
        } catch (Exception e) {
            return null;
        }
    }

    public String addCollege(Colleges college) {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            CollegeDao collegeDao = sqlSession.getMapper(CollegeDao.class);
            int result = collegeDao.addCollege(college);
            if (result > 0) {
                sqlSession.commit();
                return null;
            } else {
                System.out.println("添加失败");
                return "添加学院信息失败";
            }
        }catch (Exception e) {
            return e.getMessage();
        }
    }

    public String deleteCollege(String collegeCode) {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            // 获取映射器对象
            CollegeDao collegeDao = sqlSession.getMapper(CollegeDao.class);
            // 调用映射器方法删除学院信息
            int result = collegeDao.deleteCollege(collegeCode);
            if (result > 0) {
                sqlSession.commit();
                // 删除成功，返回null
                return null;
            } else {
                return "删除学院信息失败";
            }
        } catch (Exception e) {
            return "请检查是否仍存在相关专业等信息："+e.getMessage();
        }
    }
}
